<?php 
/* SVN FILE: $Id: users_controller.php 65 2007-12-09 00:23:22Z joe.vasquez $ */
/**
 * users controller
 * @filesource
 * @author			Joe Vasquez <joe.vasquez@gmail.com>
 * @copyright		Copyright (c) 2007, Joe Vasquez
 * @package			redlettr
 * @subpackage		users
 * @since			0.1A
 * @version			0.1A  $Rev: 65 $
 * @lastmodified	$Date: 2007-12-09 00:23:22 +0000 (Sun, 09 Dec 2007) $
 * @license			http://www.gnu.org/licenses/gpl.html GNU General Public License
 */

class UsersController extends AppController {

	var $name			= 'Users';
	var $uses			= array('User','Profile');
	var $paginate		= array('order'	=> 'User.email DESC');

/**
 * index action
 * @todo add other stuff
 */	
	function index()
	{
		//$this->Breadcrumbs->addCrumb('home');
		$this->Menu->createMenu();
		$this->Menu->addItem(array('My Profile' => '/my/profile'));		
		
		$this->pageTitle = 'Home';
	}

/**
 * view current user's profile
 */	
	function view()
	{
		if(!empty($this->Me['Profile']['displayname']))
		{
			$this->pageTitle = $this->Me['Profile']['displayname'].'\'s Profile';
		} else {
			$this->pageTitle = 'Profile';	
		}
		$this->User->id = $this->Me['User']['id'];
		
		$this->Breadcrumbs->addCrumb('home');
		$this->Breadcrumbs->addCrumb('My Profile','/my/profile');
		
		$this->Menu->createMenu();
		
		
		$this->Menu->addItem(array('Update my Profile' => '/my/profile/update'));
		
		$this->set('thisUser',$this->User->read());
	}

/**
 * update current user's profile
 */	
	function update()
	{
		$this->pageTitle = 'Update Profile';
		$msgs = array();
		$this->User->id = $this->Me['User']['id'];
		
		$this->User->expects('Profile');
		
		if(
			isset($this->data['User']['password1'])
			&&
			!empty($this->data['User']['password1'])
			&&
			isset($this->data['User']['password2']))
		{
			$password1 =  Security::hash($this->data['User']['password1']);
			if(strcmp($password1, Security::hash($this->data['User']['password2'])) == 0)
			{
				$this->data['User']['password'] = $password1;
			} else {
				$this->Session->setFlash('Uh oh, passwords don\'t match. Please try again.','error_flash');
				$this->redirect('/my/profile/update');
				exit(0);
			}
		}
		if(isset($this->data['User']))
		{
			$mrClean = new Sanitize();
			$this->data['Profile']['displayname'] = $mrClean->html(
				$this->data['Profile']['displayname'],
				true
			);
			$this->data = $mrClean->clean($this->data);
			$this->data['Profile']['id'] = $this->Me['Profile']['id'];
			$saveFields = array(
				'email', 'password', 'displayname', 'signature'
			);
			if($this->User->save($this->data,true,$saveFields))
			{
				if(isset($this->data['User']['password']))
				{
					$this->Session->setFlash('Yes!  Your profile and your password have both been updated.','information_flash');
				} else {
					$this->Session->setFlash('Yes!  Your profile has been updated.','information_flash');
				}
				$this->redirect('/my/profile');
				exit();
			} else {
				$this->Session->setFlash('Whoops, check your entries and try again.','error_flash');
				$this->set('thisUser',$this->data);
			}
		} else {
			$this->set('thisUser',$this->User->read());
		}
		
		$this->Breadcrumbs->addCrumb('home');
		$this->Breadcrumbs->addCrumb('My Profile','/my/profile');
		$this->Breadcrumbs->addCrumb('Update','/my/profile/update');

		$this->Menu->createMenu();
		$this->set('scripts',array(
				'jquery.pstrength.js',
				'tiny_mce/tiny_mce.js',
				'mce.default.js'
			)
		);
		$this->set('styles',array('jquery.pstrength'));
	}

/**
 * login
 * 
 * if user is already logged in (<em>uid</em> exists in session data), redirect
 * to index action, redirect to index on successful login
 */	
	function login()
	{
		if($this->Session->valid() && $this->Session->check('uid'))
		{
			$this->Session->setFlash('You\'re already logged in!','error_flash');
			$this->redirect('/home');
			exit();
		}
		if(!empty($this->data['User']))
		{
			$mrClean = new Sanitize();
			$this->data['User']['email'] = $mrClean->paranoid(
				$this->data['User']['email'],
				array('.','@','_','-')
			);
			if(($user = $this->User->login($this->data['User'])) !== false)
			{
				if(strcmp($user['status'],'locked') == 0)
				{
					$this->Session->setFlash('Your account has been locked, please contact the administrator.','error_flash');
					$this->redirect('/logout');
					exit();
				} else {
					if(strcmp($user['status'],'reset') == 0)
					{
						$this->Session->setFlash('Please change your password.','error_flash');
						$this->redirect('/my/profile');
						exit();
					} else {
						$this->Session->renew();
						$this->Session->write(
							'uid',
							Security::cipher($user['id'],Configure::read('Security.salt'))
						);
						$this->Session->setFlash('Welcome!','information_flash');
						$this->redirect('/home');
						exit();
					}
				}				
			} else {
				if($this->User->incrementTries($this->data['User']['email']) == true)
				{
					$this->Session->setFlash('Login failed, please try again.','error_flash');
				} else {
					$this->Session->setFlash($this->data['User']['email'].' was not found, please try again.','error_flash');
				}
			}
		}
		$this->Breadcrumbs->addCrumb('login');
	}

/**
 * logs out current user
 */	
	function logout()
	{
		$this->Session->destroy();
		$this->Session->setFlash('Goodbye.','information_flash');
		$this->redirect('/login');
		exit();
	}

/**
 * admin index
 */	
	function admin_index()
	{
		$this->set('users',$this->paginate('User'));

		$this->Menu->createMenu();
		
		$this->Menu->addItems(
			array(
				array('Create' => '/'.Configure::read('Routing.admin').'/users/create'),
				array('Search' => '/'.Configure::read('Routing.admin').'/users/search'),
			),
			'User Administration Actions'
		);
	}
	
	function admin_search(){
		if(isset($this->data))
		{
			$mrClean = new Sanitize();
			$this->data['User'] = $mrClean->paranoid($this->data['User'],array('@',' ','-','_','.'));
			$this->data['Profile'] = $mrClean->paranoid($this->data['Profile'],array('@',' ','-','_','.'));
			
			$and	= array();
			$or		= array();
			
			if(!empty($this->data['User']['email']))
			{
				if($this->data['User']['email_or'] == '1')
				{
					$or[] = array(
						'User.email' => $this->User->__makeSearchConditions(
							$this->data['User']['email'],
							$this->data['User']['email_conditions'],
							'string'
						)
					);
				} else {
					$and[] = array(
						'User.email' => $this->User->__makeSearchConditions(
							$this->data['User']['email'],
							$this->data['User']['email_conditions'],
							'string'
						)
					);
				}
			}
			if(!empty($this->data['User']['tries']) && is_numeric($this->data['User']['tries']))
			{
				if($this->data['User']['tries_or'] == '1')
				{
					$or[] = array(
						'User.tries' => $this->User->__makeSearchConditions(
							$this->data['User']['tries'],
							$this->data['User']['tries_conditions'],
							'integer'
						)
					);
				} else {
					$and[] = array(
						'User.tries' => $this->User->__makeSearchConditions(
							$this->data['User']['tries'],
							$this->data['User']['tries_conditions'],
							'integer'
						)
					);
				}
			}
			if(!empty($this->data['Profile']['displayname']))
			{
				if($this->data['Profile']['displayname_or'] == '1')
				{
					$or[] = array(
						'Profile.displayname' => $this->User->__makeSearchConditions(
							$this->data['Profile']['displayname'],
							$this->data['Profile']['displayname_conditions'],
							'string'
						)
					);
				} else {
					$and[] = array(
						'Profile.displayname' => $this->User->__makeSearchConditions(
							$this->data['Profile']['displayname'],
							$this->data['Profile']['displayname_conditions'],
							'string'
						)
					);
				}
			}
			if(!empty($this->data['Profile']['signature']))
			{
				if($this->data['Profile']['signature_or'] == '1')
				{
					$or[] = array(
						'Profile.signature' => $this->User->__makeSearchConditions(
							$this->data['Profile']['signature'],
							$this->data['Profile']['signature_conditions'],
							'string'
						)
					);
				} else {
					$and[] = array(
						'Profile.signature' => $this->User->__makeSearchConditions(
							$this->data['Profile']['signature'],
							$this->data['Profile']['signature_conditions'],
							'string'
						)
					);
				}
			}
			
			if(count($and) > 0)
			{
				$conditions = $and;
			}
			if(count($or) > 0)
			{
				$conditions = am($or);
			}
			
			if(count($conditions) > 0){
				if(is_numeric($this->data['User']['number'])){
					$this->set('results',$this->User->findAll($conditions,null,null,$this->data['User']['number']));	
				} else {
					$this->set('results',$this->User->findAll($conditions));
				}
			} else {
				$this->set('results',array());
			}
		}
		
		$this->Breadcrumbs->addCrumb('User Administration','/'.Configure::read('Routing.admin').'/users');
		$this->Breadcrumbs->addCrumb('Search','/'.Configure::read('Routing.admin').'/users/search');

		$this->Menu->createMenu();
		
		$this->set('scripts',array('jquery.ui/ui.accordion.js','jquery.easing.js'));
	}

/**
 * admin delete
 */	
	function admin_delete($uid)
	{
		$uid = intval($uid);
		if($uid == 1)
		{
			$this->log('User '.$this->Me['User']['id'].' Tried to delete the admin.');
			$this->Session->setFlash('Cannot delete the admin.','error_flash');
			$this->redirect('/'.Configure::read('Routing.admin').'/users/update/1');
			exit();
		}
		$this->__checkIfUserExists($uid);
		
		$this->User->id = $uid;
		
		if(!empty($this->data))
		{
			if(isset($this->data['User']['Confirmation']))
			{
				$this->data['User']['Confirmation'] = intval($this->data['User']['Confirmation']);
				if($this->data['User']['Confirmation'] == 1)
				{
					if($this->User->del(null,true))
					{
						$this->Session->setFlash('User deleted.');
					} else {
						$this->log('User '.$uid.'could not be deleted.');
						$this->Session->setFlash('User could not be deleted.','error_flash');
					}
					$this->redirect('/'.Configure::read('Routing.admin').'/users');
					exit();
				}
			}
			$this->redirect('/'.Configure::read('Routing.admin').'/users/update/'.$uid);
			exit();
		}
		
		$this->set('thisUser',$this->User->read());
		
		$this->Breadcrumbs->addCrumb('User Administration','/'.Configure::read('Routing.admin').'/users');
		$this->Breadcrumbs->addCrumb('User :: '.$uid,'/'.Configure::read('Routing.admin').'/users/view/'.$uid);
		$this->Breadcrumbs->addCrumb('Delete','/'.Configure::read('Routing.admin').'/users/delete/'.$uid);
	}

/**
 * admin view
 */
	function admin_view($uid)
	{
		$uid = intval($uid);
		$this->__checkIfUserExists($uid);
		
		$aro = new Aro();
		$thisAro = $aro->findByAlias('User::'.$uid);
		$aro->id = $thisAro['Aro']['parent_id'];
		$this->User->id = $uid;
		
		$this->set('userType',$aro->field('alias'));
		
		$this->set('thisUser',$this->User->read());
		
		$this->Breadcrumbs->addCrumb('User Administration','/'.Configure::read('Routing.admin').'/users');
		$this->Breadcrumbs->addCrumb('User :: '.$uid,'/'.Configure::read('Routing.admin').'/users/view/'.$uid);

		$this->Menu->createMenu();
		
		$this->Menu->addItems(
			array(
				array('update' => '/'.Configure::read('Routing.admin').'/users/update/'.$uid),
				array('delete' => '/'.Configure::read('Routing.admin').'/users/delete/'.$uid),
			),
			'User Administration Actions'
		);
	}

/**
 * admin update
 */	
	function admin_update($uid){
		$uid = intval($uid);
		$this->__checkIfUserExists($uid);
		
		$this->User->id = $uid;
		
		$aro = new Aro();
		$userTypeOptions = $aro->generateList(
			array('Aro.parent_id' => null),
			'Aro.alias ASC',
			null,
			'{n}.Aro.id',
			'{n}.Aro.alias'
		);
		$thisAro = $aro->findByAlias('User::'.$uid);
				
		if(isset($this->data['User']))
		{
			if($uid != 1){
				//first change user type
				$this->data['User']['type'] = intval($this->data['User']['type']);
				if($this->data['User']['type'] != 0)
				{
					$aro->id = $thisAro['Aro']['id'];
					$aro->saveField('parent_id', $this->data['User']['type']);
				}
				$this->data['User']['status'] = 'active';
			}
			
			//continue saving user data
			$mrClean = new Sanitize();
			$this->data['Profile']['displayname'] = $mrClean->html(
				$this->data['Profile']['displayname'], true
			); 
			$this->data = $mrClean->clean($this->data);
			$this->data['User']['id'] = $uid;
			$this->data['Profile']['id'] = $this->User->Profile->field(
				'Profile.id',
				'Profile.user_id = '.$uid
			);
			$saveFields = array(
				'email',
				'status',
				'displayname',
				'signature'
			);
			if($this->User->save($this->data,true,$saveFields))
			{
				$this->Session->setFlash('User data updated.','information_flash');
				$this->redirect('/'.Configure::read('Routing.admin').'/users/view/'.$uid);
				exit();
			} else {
				$this->Session->setFlash('Whoops, check your errors.','error_flash');
				$this->set('thisUser',$this->data);
			}
		} else {
			$this->set('thisUser',$this->User->read());
		}
		$statusOptions = $this->User->getStatusOptions();
		
		$this->Breadcrumbs->addCrumb('User Administration','/'.Configure::read('Routing.admin').'/users');
		$this->Breadcrumbs->addCrumb('User :: '.$uid,'/'.Configure::read('Routing.admin').'/users/view/'.$uid);
		$this->Breadcrumbs->addCrumb('Update','/'.Configure::read('Routing.admin').'/users/update/'.$uid);

		$this->Menu->createMenu();
		$this->Menu->addItems(
			array(
				array('update' => '/'.Configure::read('Routing.admin').'/users/update/'.$uid),
				array('delete' => '/'.Configure::read('Routing.admin').'/users/delete/'.$uid),
			),
			'User Administration Actions'
		);	
		$this->set('statusOptions',$statusOptions);
		$this->set('userTypeOptions',$userTypeOptions);
		$this->set('userType',$thisAro['Aro']['parent_id']);
		$this->set('scripts',array('tiny_mce/tiny_mce.js','mce.default.js'));
	}

/**
 * admin create
 */	
	function admin_create()
	{
		$statusOptions = $this->User->getStatusOptions();
		
		if(!empty($this->data))
		{
			$mrClean = new Sanitize();
			$this->data = $mrClean->clean($this->data);
			if($this->User->findCount(array('User.email' => $this->data['User']['email'])) > 0)
			{
				$this->Session->setFlash('This email address is already registered.','error_flash');
				$this->redirect('/'.Configure::read('Routing.admin').'/users/create');
				exit();
			}
			$this->User->create();
			$this->User->data['User'] = am($this->User->data['User'],$this->data['User']);
			if($this->User->validates())
			{
				$this->User->data['User']['password'] = Security::hash($this->User->data['User']['email']);
				if($this->User->save(null,false))
				{
					$this->User->id = $this->User->getLastInsertId();
					
					$this->User->Profile->save(array('user_id' => $this->User->id));
					$this->Profile->id = $this->Profile->getLastInsertId();
					
					$aro = new Aro();
					$thisAro = $aro->find(array('model' => 'User', 'foreign_key' => $this->User->id));
					$aro->id = $thisAro['Aro']['id'];
					$aro->save(array('parent_id' => 3,'alias' => 'User::'.$this->User->id));
					
					$this->Session->setFlash('User created.','information_flash');
					$this->redirect('/'.Configure::read('Routing.admin').'/users/update/'.$this->User->id);
					exit(0);				
				}
			} 
		}
		
		$this->set('statusOptions',$statusOptions);
		
		$this->Breadcrumbs->addCrumb('User Administration','/'.Configure::read('Routing.admin').'/users');
		$this->Breadcrumbs->addCrumb('Create User','/'.Configure::read('Routing.admin').'/users/create');
	}
/**
 * @access private
 * @param integer uid user id
 * @param bool exit redirect to admin index if user doesn't exist?
 * @return bool user does or does not exist based on user id
 */	
	function __checkIfUserExists($uid,$exit=true)
	{
		$uid = intval($uid);
		if($uid == 0 || $this->User->findCount('User.id='.$uid) < 1)
		{
			$this->log('User: '.$uid.' does not exist.');
			if($exit)
			{
				$this->Session->setFlash('User does not exist','error_flash');
				$this->redirect('/'.Configure::read('Routing.admin').'/users');
				exit();
			}
			return false;
		}
		return true;
	}
}
?>